package com.spzx.channel.service.impl;

import com.spzx.channel.service.IndexService;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.web.page.TableDataInfo;
import com.spzx.product.api.RemoteCategoryService;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.domain.Category;
import com.spzx.product.domain.vo.IndexVO;
import com.spzx.product.domain.SkuQuery;
import com.spzx.product.domain.vo.ProductSkuDetailsVO;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class IndexServiceImpl implements IndexService {
    @Resource
    RemoteProductService remoteProductService;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    @Cacheable(value ="spzx:channel:index",key = "'hotData'") //value 和key的值 拼接表示缓存的key ， key的属性值支持表达式
//value ="spzx:channel:index",key = "'hotData'"拼接的key为： spzx:channel:index::hotData
    public IndexVO selectIndexData() {

//        1、先查询缓存，如果命中直接返回
                Object result = redisTemplate.opsForValue().get("spzx:channel:index:hot");
                if(result!=null){
                    return (IndexVO) result;
                }

        //from-source -->  inner
        R<IndexVO> indexVOR = remoteProductService.listIndexVO();
        if(indexVOR.getCode()!=200){
            throw new ServiceException("远程获取热门数据失败");
        }

//        3、查询到数据，设置到缓存中保存: 必须设置缓存的过期时间
                redisTemplate.opsForValue().set("spzx:channel:index:hot",indexVOR.getData(),600,
                        TimeUnit.MINUTES);
        return indexVOR.getData();
    }

    @Resource
    RemoteCategoryService remoteCategoryService;
    @Override
    public List<Category> selectCategoryTree() {
        R<List<Category>> catesTreeR = remoteCategoryService.listCatesTree();
        if(catesTreeR.getCode()!=200){
            throw new ServiceException("远程获取分类树数据失败");
        }
        return catesTreeR.getData();
    }

    @Override
    public R<TableDataInfo> selectProductDetail(SkuQuery skuQuery) {

        return remoteProductService.skuList(skuQuery);
    }

    @Cacheable(value = "spzx:channel:index" , key = "'sku:'+#skuId")
    @Override
    public ProductSkuDetailsVO selectSkuDetails(Long skuId) {
        R<ProductSkuDetailsVO> r = remoteProductService.getSkuDetailsVO(skuId);
        if(r.getCode()!=200){
            throw new ServiceException(r.getMsg());
        }
        return r.getData();
    }

}